<template>

  <div style="width: 100%;display: flex;">
    <div style="width: 10%;">
        <el-input v-model="filterForm.business_search" @keyup.enter="handleEnter" @blur="handleEnter" @clear="handleEnter"
                        placeholder="请输入模块编码"
                        clearable
                        style="width:80%;margin-left: 10%;margin-top: 20px;"
                    />
        <div @click="select_code_action(value.system_code)" v-for="value in arrays" 
            style="width:80%;margin-left: 10%;margin-top: 20px;text-align: center;font-size: 12px;cursor: pointer;">
           <span :class="value.system_code==select_code?'on':''">{{ value.system_name }}</span> 
        </div>
    </div>  

    <div class="menu-management" style="width: 90%;">
        <!-- 筛选条件 -->
        <div class="filter-container">
            <el-form :model="filterForm" inline>
                <el-form-item label="菜单状态">
                    <el-select v-model="filterForm.status" style="width: 200px" placeholder="请选择菜单状态" clearable>
                        <el-option label="显示" :value="1" />
                        <el-option label="不显示" :value="2" />
                    </el-select>
                </el-form-item>
                
                <el-form-item label="显示状态">
                    <el-select v-model="filterForm.cache_status" style="width: 200px" placeholder="请选择缓存状态" clearable>
                        <el-option label="缓存" :value="1" />
                        <el-option label="不缓存" :value="2" />
                    </el-select>
                </el-form-item>
                
                <el-form-item label="菜单名称">
                    <el-input
                        v-model="filterForm.title"
                        placeholder="请输入菜单名称"
                        clearable
                        style="width: 200px"
                    />
                </el-form-item>
                
                <el-form-item label="模块编码" style="display: none;">
                    <el-input
                        v-model="filterForm.business"
                        placeholder="请输入模块编码"
                        clearable
                        style="width: 200px"
                    />
                </el-form-item>
                
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>


        <div class="header">
            <el-button type="primary" @click="handleAdd" v-permission="'admin:user/menu:add'">新增菜单</el-button>
        </div>
        <!-- 菜单表格 -->
        <el-table 
            :data="filteredMenuList" 
            row-key="id" 
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            v-loading="loading" style="font-size: 12px;"
        >
        <el-table-column prop="title" label="菜单名称" min-width="100"></el-table-column>
        <!-- <el-table-column prop="business" label="模块代码" ></el-table-column> -->
        <!-- <el-table-column prop="business" label="所属模块" >
            <template #default="{ row }">
            {{ businessOptions.find(item => item.value === row.business)?.label }}
            </template>
        </el-table-column> -->
        <el-table-column prop="type" label="菜单类型" width="100">
            <template #default="{ row }">
            <el-tag :type="row.type === 'directory' ? 'primary' : row.type === 'menu' ? 'success' : 'info'">
                {{ typeOptions.find(item => item.value === row.type)?.label }}
            </el-tag>
            </template>
        </el-table-column>
        <!-- <el-table-column prop="is_link" label="是否外链" width="100">
            <template #default="{ row }">
            <el-tag :type="row.is_link ? 'success' : 'info'">
                {{ row.is_link ? '是' : '否' }}
            </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="link_url" label="路由地址"  show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="components_url" label="组件路径" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column prop="permission" label="权限标识" min-width="160"  show-overflow-tooltip></el-table-column>
        <el-table-column prop="cache_status" label="缓存状态" width="100">
            <template #default="{ row }">
            <el-tag :type="row.cache_status === 1 ? 'success' : 'info'">
                {{ row.cache_status === 1 ? '缓存' : '不缓存' }}
            </el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标" width="80">
            <template #default="{ row }">
            <img v-if="row.icon" :src="row.icon || defaultIcon" class="menu-icon" alt="图标" />
            </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
            <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="2"
                @change="handleStatusChange(row)"
            />
            </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" v-permission="'admin:user/menu:edit'">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)" v-permission="'admin:user/menu:del'">删除</el-button>
            </template>
        </el-table-column>
        </el-table>

        <!-- 新增/编辑菜单对话框 -->
        <el-dialog
            :title="dialogTitle"
            v-model="dialogVisible"
            width="700px"
            :before-close="handleClose"
        >
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="100px"
            >
                <el-form-item label="所属模块" prop="business">
                  <el-select  v-model="formData.business" placeholder="请选择模块" style="width: 100%" @change="handleChange">
                      <el-option
                      v-for="item in businessOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      />
                  </el-select>
                </el-form-item>

                <el-form-item label="菜单名称" prop="title">
                <el-input
                    v-model="formData.title"
                    placeholder="请输入菜单名称（最多20字）"
                    maxlength="20"
                    show-word-limit
                />
                </el-form-item>

                <el-form-item label="父级菜单" prop="pid">
                  <el-tree-select
                      v-model="formData.pid"
                      :data="menuTreeData"
                      check-strictly
                      :render-after-expand="false"
                      placeholder="请选择父级菜单"
                      style="width: 100%"
                  />
                </el-form-item>

                <el-form-item label="菜单类型" prop="type">
                <el-radio-group v-model="formData.type">
                    <el-radio
                    v-for="item in filteredTypeOptions" 
                    :key="item.value"
                    :label="item.value"
                    >
                    {{ item.label }}
                    </el-radio>
                </el-radio-group>
                </el-form-item>

                <el-form-item label="是否外链" prop="is_link" v-if="formData.type=='menu'">
                  <el-radio-group v-model="formData.is_link">
                      <el-radio :label="true">是</el-radio>
                      <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item v-if="formData.is_link&&formData.type=='menu'" label="路由地址" prop="link_url" >
                  <el-input
                      v-model="formData.link_url"
                      placeholder="请输入路由地址（英文/数字，最多50字）"
                      maxlength="50"
                      show-word-limit
                  />
                </el-form-item>

                <el-form-item v-else label="路由地址" prop="link_url" v-if="formData.type=='menu'">
                  <el-input
                      v-model="formData.link_url"
                      placeholder="请输入路由地址（英文/数字，最多50字）"
                      maxlength="50"
                      show-word-limit
                  />
                </el-form-item>

                <el-form-item label="路由参数" prop="link_param" v-if="formData.type=='menu'">
                  <el-input
                      v-model="formData.link_param"
                      placeholder="请输入路由参数（英文/数字，最多50字）"
                      maxlength="50"
                      show-word-limit
                  />
                </el-form-item>

                <el-form-item label="组件路径" prop="components_url" v-if="formData.type=='menu'">
                  <el-input
                      v-model="formData.components_url"
                      placeholder="请输入组件路径（英文/数字，最多50字）"
                      maxlength="50"
                      show-word-limit
                  />
                </el-form-item>

                <el-form-item label="权限标识" prop="permission">
                  <el-input
                      v-model="formData.permission"
                      placeholder="请输入权限标识（英文/数字，最多50字）"
                      maxlength="50"
                      show-word-limit
                  />
                </el-form-item>

                <el-form-item label="缓存状态" prop="cache_status">
                  <el-radio-group v-model="formData.cache_status">
                      <el-radio :label="1">缓存</el-radio>
                      <el-radio :label="2">不缓存</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="菜单图标" prop="icon">
                    <input type="file" ref="fileInputRef" @change="handleFileUpload" :disabled="uploading" />
                    <div v-if="uploadProgress > 0">上传进度: {{ uploadProgress }}%</div>
                    <a style="font-size: 12px;" v-if="formData.icon" :href="formData.icon" target="_blank">查看图标</a>
                </el-form-item>

                <el-form-item label="排序" prop="sort">
                  <el-input-number
                      v-model="formData.sort"
                      :min="0"
                      :max="999"
                      controls-position="right"
                  />
                </el-form-item>

                <el-form-item label="显示状态" prop="status">
                  <el-radio-group v-model="formData.status">
                      <el-radio :label="1">显示</el-radio>
                      <el-radio :label="2">不显示</el-radio>
                  </el-radio-group>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

  </div>
  
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed,nextTick  } from 'vue'
import { menuApi, type MenuItem} from '@/api/menuApi'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { fileApi } from '@/api/user'
import { systemApi } from '@/api/system'
const fileInputRef = ref<HTMLInputElement | null>(null)


interface OptionItem {
  label: string
  value: string
}

interface FilterForm {
  business_search: string
  status: number | null
  cache_status: number | null
  title: string
  business: string
}

// 默认图标
const defaultIcon = '/default-menu-icon.png'



// 响应式数据
const menuList = ref<MenuItem[]>([])
const flatMenuList = ref<MenuItem[]>([]) // 新增：扁平菜单列表
const loading = ref(false)
const formRef = ref()
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentId = ref<number | null>(null)

const uploading = ref(false)
const uploadProgress = ref(0)

// 计算属性 - 构建树形选择器数据
const menuTreeData = computed(() => {
  if (!flatMenuList.value.length) return []
  
  const formatTree = (menus: MenuItem[], parentId: number = 0): any[] => {
    return menus
      .filter(menu => menu.pid === parentId)
      .map(menu => ({
        value: menu.id,
        label: `${menu.title} (${menu.business})`,
        disabled: isEdit.value && currentId.value === menu.id, // 编辑时不能选择自己作为父级
        children: formatTree(menus, menu.id)
      }))
  }
  
  // 添加一个虚拟的根节点来代表"顶级菜单"
  const rootOption = {
    value: 0,
    label: '顶级菜单',
    disabled: false, // 不应该禁用顶级菜单选项
    children: formatTree(flatMenuList.value, 0)
  }
  
  return [rootOption]
})


const select_code = ref()
select_code.value = 'admin'
const select_code_action = (system_code:string) => {
  filterForm.business = system_code
  select_code.value = system_code
  handleSearch()
}

const filterSystems = (text:any) => {
  if (!text) {
    return system_arrays.value
  }
  
  return system_arrays.value.filter(item => 
    item.system_name.includes(text) || 
    item.system_code.includes(text)
  )
}

const handleEnter = () => {
  const result = filterSystems(filterForm.business_search)
  arrays.value = result
}

// 加载扁平菜单列表（用于树形选择器）
const loadFlatMenuList = async () => {
  try {
    const response = await menuApi.getMenuFlatList(formData.business)
    if (response.code === 200) {
      flatMenuList.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取菜单列表失败')
  }
}

const handleChange = () => {
  formData.pid = null
  loadFlatMenuList()
};



// 筛选表单
const filterForm = reactive<FilterForm>({
  business_search:'',
  status: null,
  cache_status: null,
  title: '',
  business: ''
})

// 表单数据
const formData = reactive({
  business: '',
  title: '',
  pid: null as number | null,
  type: 'directory' as 'directory' | 'menu' | 'button',
  is_link: false,
  link_url: '',
  link_param: '',
  components_url: '',
  permission: '',
  cache_status: 1 as 1 | 2,
  icon: '',
  sort: 0,
  status: 1 as 1 | 2
})


const businessOptions = ref()
const businessOptionAction = async () => {
  try {
    const response = await menuApi.select_system()
    if (response.code === 200) {
      businessOptions.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取系统列表失败')
  }
}

// 选项数据
// const businessOptions: OptionItem[] = [
//   { label: '后台管理', value: 'admin' },
//   { label: '资产管理', value: 'asset' },
//   { label: '贷款匹配', value: 'loan' },
//   { label: '金融管理', value: 'finance' }
// ]

const typeOptions: OptionItem[] = [
  { label: '系统', value: 'system' },
  { label: '目录', value: 'directory' },
  { label: '菜单', value: 'menu' },
  { label: '按钮', value: 'button' }
]
const filteredTypeOptions = computed(() => {
  return typeOptions.filter(item => item.value !== 'system')
})

// 表单验证规则
const formRules: any = {
  business: [
    { required: true, message: '请选择所属模块', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { max: 20, message: '菜单名称不能超过20个字符', trigger: 'blur' }
  ],
  pid: [
    { required: true, message: '请选择父级菜单', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  is_link: [
    { required: true, message: '请选择是否外链', trigger: 'change' }
  ],
  link_url: [
    { message: '请输入路由地址', trigger: 'blur' },
    { max: 50, message: '路由地址不能超过50个字符', trigger: 'blur' }
  ],
  link_param: [
    { max: 50, message: '路由参数不能超过50个字符', trigger: 'blur' }
  ],
  components_url: [
    { max: 50, message: '组件路径不能超过50个字符', trigger: 'blur' }
  ],
  permission: [
    { max: 50, message: '权限标识不能超过50个字符', trigger: 'blur' }
  ],
  cache_status: [
    { required: true, message: '请选择缓存状态', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择显示状态', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑菜单' : '新增菜单')

interface SystemItem {
  system_code: string
  system_name: string
}

let arr: SystemItem[] = []
const arrays = ref<SystemItem[]>([])
const system_arrays = ref<SystemItem[]>([])

const systemloadData = async () => {
  try {
    const systemList = await systemApi.getSystemList()
    const array = systemList.list
    for(var i=0;i<array.length;i++){
        if (array[i]) {
            arr.push({
                system_code: array[i].system_code,
                system_name: array[i].system_name
            })
        }
    }
    arrays.value = arr
    system_arrays.value = arr
  } catch (error) {
    ElMessage.error('加载数据失败')
  } 
}


const filteredMenuList = computed(() => {
  // 如果没有任何筛选条件，则返回原始菜单列表
  const hasFilter = filterForm.status !== null || 
                   filterForm.cache_status !== null || 
                   filterForm.title.trim() !== '' || 
                   filterForm.business.trim() !== '';
                   
  if (!hasFilter) {
    return menuList.value;
  }
  
  // 递归过滤菜单及其子菜单
  const filterMenus = (menus: MenuItem[]): MenuItem[] => {
    return menus.filter(menu => {
      // 检查当前菜单是否符合过滤条件
      const matchesStatus = !filterForm.status || menu.status === filterForm.status;
      const matchesCacheStatus = !filterForm.cache_status || menu.cache_status === filterForm.cache_status;
      const matchesTitle = !filterForm.title || menu.title.toLowerCase().includes(filterForm.title.toLowerCase());
      const matchesBusiness = !filterForm.business || menu.business.toLowerCase().includes(filterForm.business.toLowerCase());
      
      const matchesAll = matchesStatus && matchesCacheStatus && matchesTitle && matchesBusiness;
      
      // 如果有子菜单，递归过滤子菜单
      if (menu.children && menu.children.length > 0) {
        const filteredChildren = filterMenus(menu.children);
        // 如果子菜单中有符合条件的，或者当前菜单符合条件，则保留该菜单
        return matchesAll || filteredChildren.length > 0 ? 
          {...menu, children: filteredChildren} : 
          null;
      }
      
      // 叶子节点只需检查自身是否符合条件
      return matchesAll;
    }).filter((menu): menu is MenuItem => menu !== null); // 类型守卫过滤掉null值
  };
  
  return filterMenus(menuList.value);
});

// 方法
const handleAdd = async () => {
  isEdit.value = false
  currentId.value = null
  Object.assign(formData, {
    business: '',
    title: '',
    pid: null,
    type: 'directory',
    is_link: false,
    link_url: '',
    link_param: '',
    components_url: '',
    permission: '',
    cache_status: 1,
    icon: '',
    sort: 0,
    status: 1
  })

  await loadFlatMenuList()

  // 清空文件输入框
  nextTick(() => {
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
  })
  dialogVisible.value = true
}

const handleEdit = async (row: MenuItem) => {
  isEdit.value = true
  currentId.value = row.id


  Object.assign(formData, {
    business: row.business,
    title: row.title,
    pid: row.pid !== undefined ? Number(row.pid) : null, // 确保正确处理 undefined
    type: row.type,
    is_link: row.is_link?true:false,
    link_url: row.link_url,
    link_param: row.link_param,
    components_url: row.components_url,
    permission: row.permission,
    cache_status: row.cache_status,
    icon: row.icon,
    sort: row.sort,
    status: row.status
  })

  await loadFlatMenuList()


// 清空文件输入框
  nextTick(() => {
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
  })

  dialogVisible.value = true
}


// 获取菜单列表
const loadMenuList = async (json?:any) => {
  try {
    loading.value = true
    const response = await menuApi.getMenuList(json)
    if (response.code == 200) {
      menuList.value = response.data || []
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}


const handleSearch = () => {
  loading.value = true
  
  let json = { ...filterForm }
  // 模拟搜索延迟
  setTimeout(() => {
    loading.value = false
    loadMenuList(json)
    ElMessage.success('查询完成')
  }, 500)
}

const handleReset = () => {
  Object.assign(filterForm, {
    status: null,
    cache_status: null,
    title: '',
    business: ''
  })
  ElMessage.success('已重置筛选条件')
}

const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.clearValidate()
}

// 新增菜单
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  try {
    if (isEdit.value && currentId.value) {
      // 编辑菜单
      const response = await menuApi.updateMenu(currentId.value, formData)
      if (response.code === 200) {
        ElMessage.success('编辑成功')
        loadMenuList() // 重新加载列表
        dialogVisible.value = false
      } else {
        ElMessage.error(response.message)
      }
    } else {
      // 新增菜单
      const response = await menuApi.createMenu(formData)
      if (response.code === 200) {
        ElMessage.success('新增成功')
        loadMenuList() // 重新加载列表
        dialogVisible.value = false
      } else {
        ElMessage.error(response.message)
      }
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除菜单
const handleDelete = async (row: MenuItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${row.title}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await menuApi.deleteMenu(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadMenuList() // 重新加载列表
    } else {
      ElMessage.error(response.message)
    }
  } catch {
    // 用户取消删除
  }
}

// 状态切换
const handleStatusChange = async (row: MenuItem) => {
  try {
    const response = await menuApi.updateMenuStatus(row.id, row.status)
    if (response.code === 200) {
      ElMessage.success(`状态已${row.status === 1 ? '启用' : '禁用'}`)
    } else {
      ElMessage.error(response.message)
      // 恢复原状态
      row.status = row.status === 1 ? 2 : 1
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.status = row.status === 1 ? 2 : 1
  }
}

// 处理文件上传
const handleFileUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  if (!target.files || target.files.length === 0) return

  const file = target.files[0]
  if (!file) return // 增加此判断防止 file 为 undefined

  uploading.value = true
  uploadProgress.value = 0

  try {
    const response = await fileApi.upload(file, (progress) => {
      console.log('上传进度:', progress)
    })
    if (response.code === 200) {
      uploadProgress.value = 100
      formData.icon = response.data.url
    }
  } catch (error: any) {
    console.error('文件上传失败:', error)
    alert(`文件上传失败: ${error.message}`)
  } finally {
    uploading.value = false
    uploadProgress.value = 0
  }
}



// 初始化加载
onMounted(() => {
  systemloadData()
  loadMenuList()
  loadFlatMenuList()
  businessOptionAction()
})
</script>

<style scoped>
.menu-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.menu-icon {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

.icon-upload {
  display: flex;
  align-items: center;
  gap: 12px;
}

.preview-icon {
  width: 40px;
  height: 40px;
  object-fit: contain;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 4px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px;
  margin-bottom: 0;
}

.on{
    color: #1079E6;
    font-weight: bold;
}
</style>